package com.ztrue.framework.core.command;

import com.ztrue.framework.core.domain.IAggregateRoot;
import com.ztrue.framework.core.domain.IRepository;
import com.ztrue.framework.exception.ArgumentNullException;
import com.ztrue.common.utilities.StringUtil;

import java.util.Collection;
import java.util.Hashtable;

/**
 * 命令执行上下文
 *
 * @author zhangw
 * @date 2016/10/31 16:26
 * @version: 1.0
 */
public class CommandExecuteContext implements ICommandExecuteContext {
    private Hashtable<String, IAggregateRoot> trackingAggregateRoot;
    private IRepository repository;

    public CommandExecuteContext(IRepository repository) {
        this.repository = repository;
        trackingAggregateRoot = new Hashtable<>();
    }

    /**
     * 添加一个聚合根到当前命令上下文
     *
     * @param aggregateRoot
     */
    @Override
    public void add(IAggregateRoot aggregateRoot) {
        if (aggregateRoot == null) {
            throw new ArgumentNullException("聚合根不可为空");
        }
        trackingAggregateRoot.put(aggregateRoot.getUniqueId(), aggregateRoot);
    }

    /**
     * 根据聚合根ID获取一个聚合根
     *
     * @param id
     * @return
     */
    @Override
    public <T extends IAggregateRoot> T get(String id, Class<T> cls) {
        if (StringUtil.isEmpty(id)) throw new ArgumentNullException("聚合根ID不可为空");
        T aggregateRoot = null;
        aggregateRoot = (T) trackingAggregateRoot.get(id);
        if (aggregateRoot == null) {
            aggregateRoot = repository.get(id, cls);
            if (aggregateRoot != null) trackingAggregateRoot.put(id, aggregateRoot);
        }
        return aggregateRoot;
    }

    /**
     * 获取所有跟踪的聚合根
     *
     * @return
     */
    @Override
    public Collection<IAggregateRoot> getTrackedAggregateRoots() {
        return trackingAggregateRoot.values();
    }

    /**
     * 清理跟踪的聚合根
     */
    @Override
    public void clear() {
        trackingAggregateRoot.clear();
    }
}
